import React, { useState } from "react";
import styles from "./index.module.less";

export default function Plan() {
  const [plan, setPlan] = useState({
    Monday: [],
    Tuesday: [],
    Wednesday: [],
    Thursday: [],
    Friday: [],
    Saturday: [],
    Sunday: [],
  });

  // 生成计划函数（调用 coze 工作流）
  const handleGeneratePlan = async () => {
    const userData = JSON.parse(localStorage.getItem('user')) || {}
    // console.log(userData.user)
    const age = userData.user.age;
    const weight = userData.user.weight;
    const height = userData.user.height;
    // console.log(age, weight, height)

    const goal = document.getElementById("goal").value;
    const level = document.getElementById("level").value;
    const days = document.getElementById("days").value;
    const duration = document.getElementById("duration").value;

    const body = {
      workflow_id: '7541699266747269139',
      parameters: {
        goal,
        level,
        days,
        age,
        height,
        weight,
        duration
      }
    };

    try {
      const response = await fetch('https://api.coze.cn/v1/workflow/run', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${import.meta.env.VITE_API_TOKEN}`
        },
        body: JSON.stringify(body)
      });

      const result = await response.json();
      // console.log("Coze返回结果:", result);

      if (result.code !== 0) {
        console.error("Coze API错误:", result.msg);
        alert(`生成计划失败: ${result.msg}`);
        return;
      }

      // 解析字符串格式的data
      let planText = "";

      if (result.data && typeof result.data === 'string') {
        // 使用正则表达式提取output数组中的内容
        const match = result.data.match(/output.*?\[(.*?)\]/);
        if (match && match[1]) {
          planText = match[1].replace(/"/g, '').replace(/\\/g, '');
        } else {
          // 如果正则匹配失败，尝试直接处理字符串
          planText = result.data.replace(/.*output.*?\[(.*?)\].*/s, '$1')
            .replace(/"/g, '')
            .replace(/\\/g, '');
        }
      }

      // console.log("解析后的文本:", planText);

      const planObj = {};
      const daysMap = {
        '周一': 'Monday', '周二': 'Tuesday', '周三': 'Wednesday',
        '周四': 'Thursday', '周五': 'Friday', '周六': 'Saturday', '周日': 'Sunday',
        '星期一': 'Monday', '星期二': 'Tuesday', '星期三': 'Wednesday',
        '星期四': 'Thursday', '星期五': 'Friday', '星期六': 'Saturday',
        '星期天': 'Sunday', '星期日': 'Sunday'
      };

      // 清理文本中的换行符和多余空格
      const cleanText = planText.replace(/\n/g, '').replace(/\s+/g, ' ').trim();
      // console.log("清理后的文本:", cleanText);

      // 使用正则表达式按天分割
      const dayRegex = /(周一|周二|周三|周四|周五|周六|周日)[：:](.*?)(?=(周一|周二|周三|周四|周五|周六|周日)[：:]|$)/g;

      let match;
      while ((match = dayRegex.exec(cleanText)) !== null) {
        const chineseDay = match[1];
        let content = match[2].trim();

        // 清理内容中的逗号和句号
        content = content.replace(/[，,。；;]$/, '').trim();

        const englishDay = daysMap[chineseDay];
        if (englishDay && content) {
          planObj[englishDay] = [content];
        }
      }

      // 确保所有天数都有内容
      ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'].forEach(d => {
        if (!planObj[d]) {
          planObj[d] = ['休息或自由安排'];
        }
      });

      // console.log("解析后的计划对象:", planObj);
      setPlan(planObj);

    } catch (error) {
      console.error("调用Coze API失败:", error);
      alert("生成计划失败，请检查网络或token。");
    }
  };



  return (
    <div className={styles.container}>
      {/* AI 计划生成器 */}
      <div className={`${styles.card} ${styles.aiGenerator}`}>
        <div className={styles.cardHeader}>
          <div className={styles.cardTitle}>AI个性化计划生成器</div>
          <i className="fas fa-robot"></i>
        </div>
        <div className={styles.formGroup}>
          <label htmlFor="goal">健身目标</label>
          <select id="goal">
            <option value="weightloss">减脂</option>
            <option value="muscle">增肌</option>
            <option value="strength">力量提升</option>
            <option value="endurance">耐力提升</option>
            <option value="general">保持健康</option>
          </select>
        </div>
        <div className={styles.formGroup}>
          <label htmlFor="level">健身水平</label>
          <select id="level">
            <option value="beginner">初学者</option>
            <option value="intermediate">中级</option>
            <option value="advanced">高级</option>
          </select>
        </div>
        <div className={styles.formGroup}>
          <label htmlFor="days">每周训练天数</label>
          <select id="days">
            <option value="2">2天</option>
            <option value="3">3天</option>
            <option value="4">4天</option>
            <option value="5">5天</option>
            <option value="6">6天</option>
          </select>
        </div>
        <div className={styles.formGroup}>
          <label htmlFor="duration">计划时长</label>
          <select id="duration">
            <option value="1w">1周</option>
            <option value="2w">2周</option>
            <option value="3w">3周</option>
            <option value="4w">4周</option>
            <option value="1m">1个月</option>
            <option value="2m">2个月</option>
            <option value="3m">3个月</option>
            <option value="4m">4个月</option>
            <option value="5m">5个月</option>
            <option value="6m">6个月</option>
          </select>
        </div>
        <button className={styles.btnGenerate} onClick={handleGeneratePlan}>
          <i className="fas fa-bolt"></i> 生成个性化计划
        </button>
      </div>

      {/* 我的计划（时间表样式） */}
      <div className={styles.card}>
        <div className={styles.cardHeader}>
          <div className={styles.cardTitle}>我的计划</div>
          <i className="fas fa-dumbbell"></i>
        </div>
        <div className={styles.weekDays}>
          {Object.keys(plan).map((day) => (
            <div key={day} className={styles.day}>
              <div className={styles.dayHeader}>{day}</div>
              {plan[day].length > 0 ? (
                plan[day].map((item, index) => (
                  <div key={index} className={styles.workoutItem}>
                    {item}
                  </div>
                ))
              ) : (
                <div className={styles.workoutItem}>暂无计划</div>
              )}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
